<script lang="ts" setup>
  import appStore from '@/store'
  import Monitor from '@/api/Monitor'
  import { onMounted, reactive, ref } from 'vue'
  import Fleet from './components/fleet.vue'
  import Instance from './components/instance.vue'
  import Process from './components/processes.vue'
  import Session from './components/sessions.vue'
  import { useRoute, useRouter } from 'vue-router'
  import autoScaling from '@/api/autoScaling'
  const router = useRouter()
  const route = useRoute()
  const param = reactive({
    project_id: appStore.userStore.project_id,
    offset: 1,
    limit: 10,
    fleet_id: '',
    url: ''
  })
  let searchData = {}
  interface apiData {
    name?: string
    client_session_creating_policy?: string
    created_time?: string
    creator_id?: string
    current_client_session_count?: number
    fleet_id?: string
    instance_id?: string
    ip_address?: string
    max_client_session_num?: number
    port?: number
    process_id?: string
    server_session_id?: string
    server_session_protection_policy?: string
    server_session_protection_time_limit_minutes?: number
    session_data?: string
    session_properties?: Array<object>
    state?: string
    state_reason?: string
    updated_time?: string
    bandwidth?: number
    build_id?: string
    creation_time?: string
    description?: string
    enable_auto_scaling?: boolean
    operating_system?: string
    region?: string
    resource_creation_limit_policy?: object
    scaling_interval_minutes?: number
  }
  let tableData: apiData[] = reactive([])
  let tableTotal = ref(0)
  const urlObj: { [key: string]: string } = {
    Instance: 'monitor-instances',
    Process: 'monitor-app-processes',
    Session: 'monitor-server-sessions'
  }
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  const runValue = ref(route.query.run ? route.query.run : 'Fleet')
  const dataObj: { [key: string]: string } = {
    Instance: 'instances',
    Process: 'app_processes',
    Session: 'server_sessions'
  }
  const getOtherList = async () => {
    param.url = urlObj[`${runValue.value}`]
    if (!param.fleet_id) return false
    let res = await Monitor.getMonitorList(param, searchData)
    tableTotal.value = res.data.total_count
    tableData.length = 0
    tableData.push(...res.data[dataObj[`${runValue.value}`]])
  }

  const setSearchDateFleet = (obj: object) => {
    searchData = obj
    param.offset = 1
    getFleetListByCondition()
  }

  const setSearchData = (obj: object) => {
    searchData = obj
    param.offset = 1
    getOtherList()
  }

  const runOptions = [
    {
      value: 'Fleet',
      label: 'Fleet'
    },
    {
      value: 'Instance',
      label: '实例'
    },
    {
      value: 'Process',
      label: '进程'
    },
    {
      value: 'Session',
      label: '会话'
    }
  ]

  interface optionList {
    value: string
    label: string
  }
  const notFleet = ref(route.query.run ? true : false)
  const fleetOptions: optionList[] = reactive([])
  const setFleetOptions = async () => {
    let res = await autoScaling.getFleetList(param)
    if (res.status == 200) {
      fleetOptions.length = 0
      res.data.all_fleet_ids_names.forEach((item: any) => {
        if (item.state === 'ACTIVE') {
          fleetOptions.push({
            label: `${item.name}`,
            value: item.fleet_id
          })
        }
      })
    }
  }
  const getFleetListByCondition = async () => {
    let res = await Monitor.getFleetListbyCondition(param, searchData)
    if (res.status == 200) {
      tableTotal.value = res.data.total_count
      tableData.length = 0
      tableData.push(...res.data.fleets)
    }
  }
  const getFleetList = async () => {
    let res = await Monitor.getFleetList(param, searchData)
    if (!route.query.health_state) {
      tableData.length = 0
      if (runValue.value == 'Fleet' && !notFleet.value) {
        tableTotal.value = res?.data.total_count
        tableData.push(...res?.data.fleets)
      }
    }
    setFleetOptions()
  }
  const fleetValue = ref(route.query.id ? route.query.id : '')
  const changeRun = (run: string) => {
    param.offset = 1
    tableData.length = 0
    searchData = {}
    router.push({ name: 'runningState', query: { run } })
    run === 'Fleet' ? ((notFleet.value = false), getFleetList()) : ((notFleet.value = true), getOtherList())
  }
  const changeFleet = (fleet: string) => {
    param.offset = 1
    param.fleet_id = fleet
    getOtherList()
  }

  const buildFleet = () => {
    router.push({ name: 'createFleet' })
  }
  if (route.query.id) {
    if (typeof route.query.id == 'string') {
      param.fleet_id = route.query.id
    }
  }
  getFleetList()
  const small = ref(false)
  const disabled = ref(false)
  const background = ref(true)
  const handleSizeChange = (val: number) => {
    param.limit = val
    param.offset = 1
    notFleet.value ? getOtherList() : getFleetList()
  }
  const handleCurrentChange = (val: number) => {
    param.offset = val
    notFleet.value ? getOtherList() : getFleetList()
  }
</script>
<template>
  <div id="runningState" class="list-index">
    <div class="run-box">
      <div class="state-box">
        <div class="run-label">运行状态</div>
        <div class="run-select">
          <el-select v-model="runValue" placeholder="请选择运行状态" @change="changeRun">
            <el-option v-for="item in runOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="fleetValue" class="m-2 fleet" placeholder="请选择fleet" @change="changeFleet" v-if="notFleet">
            <el-option v-for="item in fleetOptions" :key="item.value" :label="item.label" :value="item.value">
              <div class="fleetLabel">{{ item.label }}</div>
              <div class="fleetValue">{{ item.value }}</div>
            </el-option>
          </el-select>
        </div>
      </div>
    </div>
    <div class="top-button" v-if="userType >= 5">
      <button class="btn new" @click="buildFleet">新建Fleet</button>
    </div>
    <Fleet v-if="runValue === 'Fleet'" @fupdate="setSearchDateFleet" :data="tableData"></Fleet>
    <Instance v-else-if="runValue === 'Instance'" @fupdate="setSearchData" :data="tableData"></Instance>
    <Process v-else-if="runValue === 'Process'" @fupdate="setSearchData" :data="tableData"></Process>
    <Session @fupdate="setSearchData" v-else :data="tableData"></Session>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="param.offset"
        v-model:page-size="param.limit"
        :page-sizes="[10, 20, 50, 100]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/list.scss';
  @import '@/assets/scss/dropdownBox.scss';
</style>
